class Solution
{
public:
    vector<int> nextGreaterElements(vector<int> &nums)
    {
        stack<int> q;
        int n = nums.size();
        for (int i = n - 1; i >= 0; --i)
        {
            while (!q.empty())
            {
                if (q.top() <= nums[i])
                {
                    q.pop();
                }
                else
                {
                    break;
                }
            }
            q.push(nums[i]);
        }
        vector<int> result(n);
        for (int i = n - 1; i >= 0; --i)
        {
            while (!q.empty())
            {
                if (q.top() <= nums[i])
                {
                    q.pop();
                }
                else
                {
                    break;
                }
            }
            if (q.empty())
            {
                result[i] = -1;
            }
            else
            {
                result[i] = q.top();
            }
            q.push(nums[i]);
        }
        return result;
    }
};